/**
 * 
 */
package com.hu.ta.assignment5.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * @author cage@g.com
 */
public class FileTxt extends FileIO {

	private static final long serialVersionUID = -7868526311435144873L;

	/**
	 * @param path
	 */
	public FileTxt(String path) {
		super(path);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hu.ta.assignment3.io.FileIO#read()
	 */
	@Override
	public boolean read() {
		try {
			BufferedReader inputSource = new BufferedReader(
					new InputStreamReader(
							new FileInputStream(getAbsoluteFile()), "UTF-8"));
			String line = null;
			while (inputSource.ready()) {
				line = inputSource.readLine().trim();
				if (0 < line.length()) {
					text.addLine(line);
				}
			}
			inputSource.close();
			return true;
		} catch (IOException e) {
			System.out.println(String.format("Cannot read the file (%s)",
					getAbsolutePath()));
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hu.ta.assignment3.io.FileIO#write()
	 */
	@Override
	public boolean write() {
		try {
			BufferedWriter outputSource = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(
							getAbsoluteFile()), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < text.size(); i++) {
				buffer.append(" ");
				String token = text.getLine(i);
				if (token.startsWith("./")) {
					outputSource.write("\t" + buffer + "./.\n\n\n");
					buffer = new StringBuffer();
				} else {
					buffer.append(token);					
				}
			}
			outputSource.close();
			return true;
		} catch (IOException e) {
			System.out.println(String.format("Cannot write the file (%s)",
					getAbsolutePath()));
		}
		return false;
	}

}
